<script setup lang="ts">
import { reactive, ref } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import {
  get_specs_list_api,
  get_specs_date_list_api,
} from "@/package/mall/api/tour_product";
import { Date } from "@/utils/date";
import { Account } from "@/utils/account";
import { Router } from "@/utils/router";
import { Toast } from "@/utils/toast";

import PackageCheckState from "./components/package-check-state.vue";
import DetailDateItem from "./components/detail-date-item.vue";
import DetailDateMore from "./components/detail-date-more.vue";
import PackageStarList from "./components/package-star-list.vue";
import OrderSettleBar from "../goods/components/order-settle-bar.vue";
import PopupCenter from "@/components/popup/center.vue";
import PackageDatePicker from "./components/package-date-picker.vue";

onLoad((options) => {
  tempData.id = options?.id;
  infoData.name = decodeURIComponent(options?.name || "");

  if (options?.date) {
    specData.date = options.date;
    getDateList();
    getSpecList().then(() => setInitCondition("guider_level"));
  } else {
    getDateList();
    getSpecList();
  }

  tempData.guiderId = options?.guiderId;
});

const getDateList = () => {
  return get_specs_date_list_api({
    product_id: tempData.id,
    specs_id: specData.id,
  }).then((resp) => {
    const currentDate = Date.getCurrentDate(Date.ftDate);
    // 处理日历数据
    tempData.dateList = resp.items.map((i) => {
      const date = Date.getDate(i.date);
      return {
        ...i,
        month: date.format(Date.ftMonth),
        isToday: i.date === currentDate ? 1 : 2, // 1：今日；2：今日之后；undefined：今日之前
        date_str: date.format("MM-DD"),
        week_str:
          i.date === currentDate
            ? "今天"
            : date.subtract(1, "day").format(Date.ftDate) === currentDate
            ? "明天"
            : `周${["日", "一", "二", "三", "四", "五", "六"][date.day()]}`,
      };
    });
    dateList.value = tempData.dateList.slice(0, 3);
  });
};
const getSpecList = () => {
  return get_specs_list_api({
    product_id: tempData.id,
    date: specData.date,
  }).then((resp) => {
    tempData.sepcList = resp.items;
    sepcList.value = tempData.sepcList;
  });
};

const infoData = reactive({ name: "" });

const dateList = ref<any[]>([]);
const dateClick = (index: number) => {
  const checkFn = (date: any, callback: () => void) => {
    !date.isToday || date.status === 0
      ? Toast.show("该日期不可约")
      : date.status === 3
      ? Toast.show("该日期已约满")
      : callback();
  };

  if (index === -1) {
    // 更多
    packageDatePicker.value?.show(
      { value: specData.date, data: tempData.dateList },
      (date, close) => {
        checkFn(date, () => {
          specData.date = date.date;
          // 处理第3个日期项，index 不等于 0，1
          const index = dateList.value.findIndex((i) => i.date === date.date);
          dateList.value.splice(
            2,
            1,
            index === 0 || index === 1 ? tempData.dateList[2] : date
          );

          // 刷新规格列表
          getSpecList().then(() => setInitCondition("guider_level"));
          close();
        });
      }
    );
  } else {
    const date = dateList.value[index];
    checkFn(date, () => {
      specData.date = date.date;
      // 刷新规格列表
      getSpecList().then(() => setInitCondition("guider_level"));
    });
  }
};

const setInitCondition = (key: string) => {
  if (getConditionDisabled(key, 0)) {
    const valueList =
      key === "guider_level"
        ? levelList
        : key === "group_type"
        ? typeList
        : sessionList;
    const condition = valueList.find((i) => {
      return !getConditionDisabled(key, i.id);
    });
    if (condition) setConditionValue(key, condition.id);
  } else {
    setConditionValue(key, 0);
  }
};
const setConditionValue = (key: string, value: number) => {
  (conditionData as any)[key] = value;

  // 设置套餐列表
  sepcList.value = tempData.sepcList.filter((i) => {
    return (
      (conditionData.guider_level
        ? conditionData.guider_level === i.guider_level
        : true) &&
      (conditionData.group_type
        ? conditionData.group_type === i.group_type
        : true) &&
      (conditionData.session_id
        ? conditionData.session_id === i.session_id
        : true)
    );
  });
  // 已选套餐，判断套餐是否存在，不存在，重置
  if (specData.id) {
    const spec = sepcList.value.find((i) => i.id === specData.id);
    if (spec) {
      specData.price = spec.price;
      // 刷新折扣
    } else {
      specData.id = "";
    }
  }

  // 设置默认条件
  if (key === "guider_level") setInitCondition("group_type");
  else if (key === "group_type") setInitCondition("session_id");
};

const conditionData = reactive({
  guider_level: "",
  group_type: "",
  session_id: "",
});
const getConditionDisabled = (key: string, value: any) => {
  if (!specData.date) return false;

  let sepcList: any[] = [];
  if (key === "guider_level") {
    sepcList = tempData.sepcList;
  } else {
    sepcList = tempData.sepcList.filter((i) => {
      return conditionData.guider_level
        ? conditionData.guider_level === i.guider_level
        : true;
    });
    if (key === "session_id") {
      sepcList = sepcList.filter((i) => {
        return conditionData.group_type
          ? conditionData.group_type === i.group_type
          : true;
      });
    }
  }

  // 单个是否禁用
  const checkFn = (value: number) => {
    return sepcList.every((i) => i[key] !== value);
  };

  if (value) return checkFn(value);

  const valueList =
    key === "guider_level"
      ? levelList
      : key === "group_type"
      ? typeList
      : sessionList;

  return valueList.filter((i) => !checkFn(i.id)).length <= 1;
};
const conditionClick = (key: string, value: number) => {
  if (getConditionDisabled(key, value)) return;
  if (!specData.date) return Toast.show("请选择出行日期");
  if (key !== "guider_level" && conditionData.guider_level === "")
    return Toast.show("请选择讲师");
  if (conditionData.group_type === "") return Toast.show("请选择团型");

  setConditionValue(key, value);
};

const levelList = [
  { id: 1, name: "殿堂级", num: 5 },
  { id: 2, name: "精英级", num: 4 },
  { id: 3, name: "专业级", num: 3 },
];
const typeList = [
  { id: 2, name: "私家团" },
  { id: 1, name: "拼团" },
];
const sessionList = [
  { id: 1, name: "上午场" },
  { id: 2, name: "下午场" },
  { id: 3, name: "一日游" },
];

const levelVisible = ref(false);
const typeVisible = ref(false);

const specData = reactive({
  id: "",
  name: "",
  date: "",
  price: "",
  type: "",
});
const sepcList = ref<any[]>([]);
const specClick = (index: number) => {
  if (!specData.date) return Toast.show("请选择出行日期");
  const spec = sepcList.value[index];
  specData.id = spec.id;
  specData.name = `${spec.guider_level_str} | ${spec.group_type_str} | ${spec.name}`;
  specData.price = spec.price;
  specData.type = spec.group_type;
  // 刷新价格日历价格
  getDateList().then(() => {
    // 处理第3个日期项，index 不等于 0，1
    const date = tempData.dateList.find((i) => i.date === specData.date);
    const index = dateList.value.findIndex((i) => i.date === date.date);
    dateList.value.splice(
      2,
      1,
      index === 0 || index === 1 ? tempData.dateList[2] : date
    );
  });
};

const btnClick = () => {
  if (!(specData.id && specData.date)) return;

  Account.checkLogin((isLogin) => {
    Router.navigateToOrRedirectTo(
      isLogin,
      `/package/mall/pages/jps/order?${Router.dataToQuery({
        id: specData.id,
        specs_name: specData.name,
        use_date: specData.date,
        price: specData.price,
        group_type: specData.type,
        product_name: infoData.name,
        guiderId: tempData.guiderId,
      })}`
    );
  });
};

const packageDatePicker = ref<InstanceType<typeof PackageDatePicker>>();
const tempData = {
  id: "",
  dateList: [] as any[], // 价格日历
  sepcList: [] as any[], // 规格列表
  guiderId: "",
};
</script>

<template>
  <view class="package-bg"></view>

  <view class="package-info">
    <view class="package-info-name">{{ infoData.name }}</view>
    <view
      class="package-info-spec"
      :style="{ color: specData.id ? '#4e9b93' : '#666666' }"
    >
      {{
        specData.id
          ? `已选：${specData.name}`
          : "请由上至下选择出行日期、讲师级别、团型、场次、套餐"
      }}
    </view>
  </view>

  <view class="package-form">
    <view class="package-form-title">选择日期</view>
    <view class="package-form-content package-date">
      <view style="display: flex; flex-grow: 1; min-width: 0">
        <view
          class="package-date-item"
          v-for="(i, d) of dateList"
          :key="i.date"
          @click="dateClick(d)"
        >
          <PackageCheckState :isCheck="specData.date === i.date">
            <DetailDateItem :info="i" />
          </PackageCheckState>
        </view>
      </view>
      <view class="package-date-more" @click="dateClick(-1)">
        <DetailDateMore />
      </view>
    </view>

    <view class="package-form-title">
      选择讲师
      <image
        class="package-form-question"
        src="@/package/mall/static/jps-package-question.png"
        @click="levelVisible = true"
      />
    </view>
    <view class="package-form-content package-level">
      <view
        class="package-form-item"
        @click="conditionClick('guider_level', 0)"
      >
        <PackageCheckState
          :isCheck="conditionData.guider_level === 0"
          :disabled="getConditionDisabled('guider_level', 0)"
        >
          <view class="package-form-radio">全部</view>
        </PackageCheckState>
      </view>
      <view
        class="package-form-item"
        v-for="i of levelList"
        :key="i.id"
        @click="conditionClick('guider_level', i.id)"
      >
        <PackageCheckState
          :isCheck="conditionData.guider_level === i.id"
          :disabled="getConditionDisabled('guider_level', i.id)"
        >
          <view class="package-level-item">
            {{ i.name }}
            <PackageStarList :modelValue="i.num" />
          </view>
        </PackageCheckState>
      </view>
    </view>

    <view class="package-form-title">
      选择团型
      <image
        class="package-form-question"
        src="@/package/mall/static/jps-package-question.png"
        @click="typeVisible = true"
      />
    </view>
    <view class="package-form-content">
      <view class="package-form-item" @click="conditionClick('group_type', 0)">
        <PackageCheckState
          :isCheck="conditionData.group_type === 0"
          :disabled="getConditionDisabled('group_type', 0)"
        >
          <view class="package-form-radio">全部</view>
        </PackageCheckState>
      </view>
      <view
        class="package-form-item"
        v-for="i of typeList"
        :key="i.id"
        @click="conditionClick('group_type', i.id)"
      >
        <PackageCheckState
          :isCheck="conditionData.group_type === i.id"
          :disabled="getConditionDisabled('group_type', i.id)"
        >
          <view class="package-form-radio">{{ i.name }}</view>
        </PackageCheckState>
      </view>
    </view>

    <view class="package-form-title">选择场次</view>
    <view class="package-form-content">
      <view class="package-form-item" @click="conditionClick('session_id', 0)">
        <PackageCheckState
          :isCheck="conditionData.session_id === 0"
          :disabled="getConditionDisabled('session_id', 0)"
        >
          <view class="package-form-radio">全部</view>
        </PackageCheckState>
      </view>
      <view
        class="package-form-item"
        v-for="i of sessionList"
        :key="i.id"
        @click="conditionClick('session_id', i.id)"
      >
        <PackageCheckState
          :isCheck="conditionData.session_id === i.id"
          :disabled="getConditionDisabled('session_id', i.id)"
        >
          <view class="package-form-radio">{{ i.name }}</view>
        </PackageCheckState>
      </view>
    </view>

    <view class="package-form-title">选择套餐（{{ sepcList.length }}）</view>
    <view class="package-spec">
      <view
        class="package-spec-item"
        v-for="(i, d) of sepcList"
        :key="i.id"
        @click="specClick(d)"
      >
        <PackageCheckState :isCheck="specData.id === i.id">
          <view class="package-spec-text">{{ i.name }}</view>
        </PackageCheckState>
      </view>
    </view>
  </view>

  <view class="package-fixed">
    <OrderSettleBar
      :price="specData.id && specData.date ? specData.price : '--'"
      :unit="`/${specData.type === 1 ? '位' : '团'}`"
      btnText="下一步"
      :disabled="!(specData.id && specData.date)"
      @btn-click="btnClick"
    />
  </view>

  <PopupCenter v-model="levelVisible" title="讲解老师资质说明">
    <view class="package-question">
      <view class="package-question-label">
        殿堂级&nbsp;<PackageStarList :modelValue="5" size="24rpx" />
      </view>
      <view class="package-question-text">
        特级导游、国家级金牌、文博领域专家等
      </view>
      <view class="package-question-label">
        精英级&nbsp;<PackageStarList :modelValue="4" size="24rpx" />
      </view>
      <view class="package-question-text">
        持国家中/高级导游证书、国家/省/市级金牌导游
      </view>
      <view class="package-question-label">
        专业级&nbsp;<PackageStarList :modelValue="3" size="24rpx" />
      </view>
      <view class="package-question-text">
        持国家初/中级导游证书、专业讲解员、资深历史爱好者
      </view>
    </view>
  </PopupCenter>

  <PopupCenter v-model="typeVisible" title="团型说明">
    <view class="package-question">
      <view class="package-question-label">私家团</view>
      <view class="package-question-text">
        专为私人小团体或家庭提供1V1服务的深度讲解参观团，常规人数限在1-6人
      </view>
      <view class="package-question-label">拼团</view>
      <view class="package-question-text">与他人拼场，每团人数不超过12人</view>
    </view>
  </PopupCenter>

  <PackageDatePicker ref="packageDatePicker" />
</template>

<style lang="scss">
page {
  padding-top: 30rpx;
  padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
}

.package-bg {
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  height: 348rpx;
  background: linear-gradient(
    180deg,
    #fa8831,
    #fa8831 52%,
    rgba(255, 255, 255, 0)
  );
}

.package-info {
  position: relative;
  padding: 30rpx;
  margin: 0 30rpx 20rpx;
  border-radius: 20rpx;
  background-color: #ffffff;

  .package-info-name {
    margin-bottom: 20rpx;
    font-size: 30rpx;
    color: #2d2d2d;
    line-height: 48rpx;
    font-weight: bold;
  }

  .package-info-spec {
    font-size: 24rpx;
    line-height: 44rpx;
  }
}

.package-form {
  position: relative;
  padding-left: 30rpx;
  padding-top: 30rpx;
  margin: 0 30rpx;
  border-radius: 20rpx;
  background-color: #ffffff;

  .package-form-title {
    display: flex;
    align-items: center;
    margin-bottom: 30rpx;
    font-size: 30rpx;
    color: #000000;
    line-height: 42rpx;
    font-weight: bold;
  }

  .package-form-content {
    display: flex;
    // align-items: center;
    margin-bottom: 40rpx;
  }

  .package-form-question {
    width: 32rpx;
    height: 32rpx;
    margin-left: 16rpx;
  }

  .package-form-item {
    margin-right: 10rpx;
  }

  .package-form-radio {
    min-width: 112rpx;
    padding: 20rpx;
    font-size: 28rpx;
    color: #2d2d2d;
    line-height: 44rpx;
    text-align: center;
  }
}

.package-date {
  padding-right: 30rpx;

  .package-date-item {
    flex-grow: 1;
    width: 33.33%;
    padding: 2rpx 0;
    margin-right: 12rpx;
  }

  .package-date-more {
    flex-shrink: 0;
    width: 94rpx;
    height: 88rpx;
    border-radius: 10rpx;
    border: 2rpx solid #eeeeee;
  }
}

.package-level {
  .package-level-item {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    min-width: 112rpx;
    padding: 14rpx 20rpx;
    font-size: 28rpx;
    color: #2d2d2d;
    line-height: 44rpx;
  }
}

.package-spec {
  padding-right: 30rpx;
  padding-bottom: 1rpx;

  .package-spec-item {
    margin-bottom: 20rpx;
  }

  .package-spec-text {
    padding: 20rpx;
    font-size: 28rpx;
    color: #2d2d2d;
    line-height: 44rpx;
  }
}

.package-fixed {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 104rpx;
  padding-top: 16rpx;
  padding-bottom: env(safe-area-inset-bottom);
  background-color: #ffffff;
  z-index: 8;
}

.package-question {
  width: 500rpx;
  padding: 0 50rpx 30rpx;

  .package-question-label {
    display: flex;
    align-items: center;
    margin-bottom: 8rpx;
    font-size: 30rpx;
    color: #ff7900;
    line-height: 46rpx;
  }

  .package-question-text {
    margin-bottom: 30rpx;
    font-size: 26rpx;
    color: #666666;
    line-height: 46rpx;
  }
}
</style>